﻿using System;
using System.ComponentModel.Composition;
using System.Globalization;
using System.Linq;
using System.Windows.Data;
using Bazookabird.Common;
using Bazookabird.Common.Plugin;
using Bazookabird.Wpf.Model;

namespace Bazookabird.Wpf.Builds.BuildHandlers
{
    [Export(typeof(IBuildHandler))]
    [PartCreationPolicy(CreationPolicy.NonShared)]
    public class SimpleBuildHandlerViewModel : PanelViewModelBase, IBuildHandler, IRefresh
    {
        public override string Description { get { return "yada yada yada"; } }

        public string Name { get { return "Simple build viewer"; } }

        protected override void OnActivate()
        {
            base.OnActivate();
            DisplayName = Name;
        }

        public BuildHandlerType BuildHandlerType { get { return BuildHandlerType.Single; } }

        private BuildDefinitionWrapper _buildDefinition;
        public BuildDefinitionWrapper BuildDefinition
        {
            get { return _buildDefinition; }
            set 
            { 
                _buildDefinition = value; 
                NotifyOfPropertyChange(() => BuildDefinition);
                Refresh();
            }
        }

        private BuildDetailWrapper[] _details;
        public BuildDetailWrapper[] Details
        {
            get { return _details; }
            set
            {
                _details = value;
                NotifyOfPropertyChange(() => Details);
                NotifyOfPropertyChange(() => LastBuild);
            }
        }

        public BuildDetailWrapper LastBuild
        {
            get { return Details == null ? null : Details.Where(d => d.BuildFinished).OrderBy(d => d.FinishTime).FirstOrDefault(); }
        }

        private DateTime? _lastUpdated;
        public DateTime? LastUpdated
        {
            get { return _lastUpdated; }
            set
            {
                _lastUpdated = value;
                NotifyOfPropertyChange(() => LastUpdated);
            }
        }

        public new void Refresh()
        {
            Details = BuildDefinition.QueryBuilds();
            LastUpdated = DateTime.Now;
            base.Refresh();
        }
    }

    public class GetFieldByIdConverter : IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        { // ReferenceName
            var itemNode = value as WorkItemNode;
            if (itemNode == null || itemNode.WorkItem == null) return "?";

            var stringParameter = parameter as string ?? "";

            var field = itemNode.WorkItem.Fields[stringParameter];            
            return field.IsValid ? field.Value : value;
        }

        public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
        {
            throw new NotImplementedException();
        }
    }
}
